Find and count connected components in binary image.
Description
Finds and counts the connected components in the binary image BW. The function returns a structure containing the total number of connected components, such as regions of interest (ROIs), in the image and the pixel indices assigned to each component.
Parameters
BW: Binary 2D image. For numeric input, any nonzero pixels are considered to be 1 (true).
8 — 8-connected neighborhood (edge and corner connectivity)
Alternatively, can be a connectivity array of 0s and 1s with the same dimensionality as BW. The 1-valued elements define neighborhood locations relative to the center element. The center element must be 1. The connectivity array size must be odd along each dimension.
Returns
Connected components, specified as a structure with the following fields:
Field
Description
connectivity
Connectivity of the connected components
image_size
Size of the binary image
num_objects
Number of connected components in the binary image
Vector where each element contains the linear indices of the pixels in each object
centroid
A Float64 Matrix with the x,y coordinates of the centroids for each component
area
A vector of Float64 with the areas of each component
To compute a label matrix with a memory-efficient data type (for instance, UInt8 versus Float64), use the labelmatrix function on the output of bwconncomp:
CC =bwconncomp(BW)L =labelmatrix(CC)
Examples
Find Connected Components in Binary Image
usingGMT# Create a binary imageBW = [110000001101100000011000000001100000011000000000]# Find connected componentsCC =bwconncomp(BW)println("Number of connected components: ", CC.num_objects)
Number of connected components: 2
Specify Connectivity
Find connected components using 4-connectivity instead of the default 8-connectivity:
usingGMTBW = [110000001101100000011000000001100000011000000000]# 4-connectivityCC4 =bwconncomp(BW, conn=4)println("Number of components (4-conn): ", CC4.num_objects)# 8-connectivityCC8 =bwconncomp(BW, conn=8)println("Number of components (8-conn): ", CC8.num_objects)
Number of components (4-conn): 3
Number of components (8-conn): 2
Extract Properties of Connected Components
Use the output structure to analyze individual components:
usingGMTBW = [110000001101100000011000000001100000011000000000]CC =bwconncomp(BW)# Number of pixels in each componentnumPixels = [length(CC.pixel_list[i]) for i in1:CC.num_objects]println("Pixels per component: ", numPixels)# Find the largest componentlargest =argmax(numPixels)println("Largest component is #", largest, " with ", numPixels[largest], " pixels")
Pixels per component: [4, 8]
Largest component is #2 with 8 pixels